package com.guxingke.gsb.config;

import com.guxingke.gsb.util.PathUtil;
import com.moandjiezana.toml.Toml;
import org.apache.commons.lang3.text.StrBuilder;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * Created by 孤星可 on 2015/11/22.
 *
 * @author guxingke
 * @since 2015/11/22
 */
public class Config {
    private static Toml toml = new Toml();
    private static String globalConfigPath;

    private static String siteConfigPath;

    private static String themeConfigPath;

    private static ThemeConfig themeConfig;

    public static void init(String globalConfigPath) {
        Config.globalConfigPath = globalConfigPath;
        Config.siteConfigPath = initGlobalConfig();
        Config.themeConfigPath = initSiteConfig();
        Config.themeConfig = initThemeConfig();
    }

    public static String getThemeConfigPath() {
        return PathUtil.toJavaPath(themeConfigPath);
    }

    public static ThemeConfig getThemeConfig() {
        return themeConfig;
    }

    private static String initGlobalConfig() {
        Path globalPath = Paths.get(globalConfigPath, Constant.GLOBAL_CONFIG_FILENAME);
        Toml globalConfig = toml.parse(globalPath.toFile());
        List<String> sitePath = globalConfig.getList("sitePath");
        String defaultSitePath = buildPath(sitePath);
        return defaultSitePath;
    }

    private static String buildPath(List<String> sitePath) {
        StringBuilder sb = new StringBuilder();
        for (String s : sitePath) {
            sb.append(s);
            sb.append(File.separator);
        }
        return sb.toString();
    }

    private static String initSiteConfig() {
        Path sitePath = Paths.get(siteConfigPath, "config.toml");
        Toml siteConfig = toml.parse(sitePath.toFile());
        String theme = siteConfig.getString("theme");
        return siteConfigPath + "themes" + File.separator + theme;
    }

    private static ThemeConfig initThemeConfig() {
        Path themePath = Paths.get(themeConfigPath, "theme.toml");
        Toml to = toml.parse(themePath.toFile());
        ThemeConfig themeConfig = toml.parse(themePath.toFile()).to(ThemeConfig.class);
        return themeConfig;
    }

    public static String getSiteConfigPath() {
        return siteConfigPath;
    }
}
